package cn.tedu.exception.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {

    /**
     * 限流 熔断 热点 返回
     * @param httpServletRequest
     * @param response
     * @param e
     * @throws Exception
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        if(e instanceof DegradeException){
            map.put("status",601);
            map.put("message","服务被熔断了");
        }else if(e instanceof FlowException){
            map.put("status",602);
            map.put("message","服务被限流了");
        }else if(e instanceof ParamFlowException){
            map.put("status",603);
            map.put("message","该商品太火爆了,请稍后重试");
        }else{
            map.put("status",604);
            map.put("message","Blocked by Sentinel(flow limiting)");
        }
        String jsonResult = new ObjectMapper().writeValueAsString(map);
        pw.println(jsonResult);
        pw.flush();
    }
}
